const router = require("koa-router")();
const main = require("../models")
router.get("/login",async ctx=>{
    // ctx.body = "login"
    var arr = ["html","css","js"]
    await ctx.render("login",{arr})
})
router.get("/register",async ctx=>{
    await ctx.render("register")
})
router.get("/home",async ctx=>{
    ctx.body = "首页"
})
router.post("/doRegister",async ctx=>{
    console.log(ctx.request.body)
    var {username,pwd} = ctx.request.body;
    var userCollection  =await  main("user");
    // 对user查询，没有username才添加
    var res =await userCollection.find({username}).toArray();
    console.log(res);
    // 用户名存在，还在注册界面呆着
    if(res.length){
        ctx.body="<script>alert('用户名和密码已经被注册');location.href='/register'</script>"

    }else{
        //2 用户名不存在，注册-进入首页
        var res = await userCollection.insertOne({username,pwd});
        ctx.body="<script>alert('注册成功，恭喜进入首页');location.href='/register'</script>"
    }
    // var res = await userCollection.insertOne({username,pwd});
    // console.log(res)
})
router.post("/doLogin",async ctx=>{
    var {username,pwd} = ctx.request.body
    var userCollection = await main("user")
    var res = await userCollection.find({username,pwd}).toArray();
    console.log(res);
    if(res.length){
        await ctx.redirect("/home")
    }else{
        ctx.body="<script>alert('用户名或密码错误');location.href='/login'</script>"
    }
})
module.exports=router;